﻿using QuanLyGiaoVuDAL.DTO;
using QuanLyGiaoVuService.CommandServices;
using QuanLyGiaoVuService.CommonServices;
using QuanLyGiaoVuService.ReportServices;
using QuanLyGiaoVuUI.Extensions.ExtendedAttributes;
using QuanLyGiaoVuUI.Extensions.Utilities;
using QuanLyGiaoVuUI.Models.TaiLieu;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QuanLyGiaoVuUI.Controllers
{
    [GiangVienAuthorize]
    [HandleError]
    public class TaiLieuController : Controller
    {
        private ITaiLieuReportService _taiLieuReportService;
        private ITaiLieuCommandService _taiLieuCommandService;
        private IFileService _fileService;
        private IQuanLyQuyenTruyCapService _quyenTruyCapService;
        private IThamSoService _thamSoService;

        public TaiLieuController(ITaiLieuReportService taiLieuReportService, ITaiLieuCommandService taiLieuCommandService, IFileService fileService, IQuanLyQuyenTruyCapService quyenTruyCapService, IThamSoService thamSoService)
        {
            _taiLieuReportService = taiLieuReportService;
            _taiLieuCommandService = taiLieuCommandService;
            _fileService = fileService;
            _quyenTruyCapService = quyenTruyCapService;
            _thamSoService = thamSoService;
        }

        public ActionResult Index()
        {
            ViewData["maNguoiDung"] = UserUtility.GetCurrentUser().MaNguoiDung;
            return View();
        }

        [HttpGet]
        public JsonResult GetThuMuc(Guid? maThuMucCha)
        {
            List<ThuMucDTO> danhSachThuMuc = _taiLieuReportService.GetAllThuMucByMaThuMucCha(maThuMucCha).ToList();
            List<JsTreeNode> nodesList = new List<JsTreeNode>();
            foreach (ThuMucDTO thuMuc in danhSachThuMuc)
            {
                JsTreeNode node = new JsTreeNode();
                node.attr = new Attributes();
                node.attr.id = thuMuc.MaThuMuc.ToString();
                node.attr.rel = "folder";
                node.data = thuMuc.TenThuMuc;
                node.state = "closed";
                nodesList.Add(node);
            }
            return Json(nodesList.ToArray(), JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult TaoThuMuc()
        {
            TaoThuMucViewModel viewModel = new TaoThuMucViewModel();
            viewModel.DanhSachThuMuc = _taiLieuReportService.GetThuMuc(null);
            return View(viewModel);
        }

        [HttpPost]
        public JsonResult TaoThuMuc(TaoThuMucViewModel viewModel)
        {
            object jsonData;
            if (ModelState.IsValid)
            {
                _taiLieuCommandService.TaoThuMucMoi(UserUtility.GetCurrentUser().MaNguoiDung, viewModel.ToThuMucDTO());
                jsonData = new
                {
                    success = true,
                    message = "Tạo thư mục thành công!"
                };
            }
            else jsonData = new
            {
                success = false,
                message = "Tạo thư mục không thành công!"
            };
            return Json(jsonData); 
        }

        [HttpPost]
        public JsonResult DoiTenThuMuc(Guid? maThuMuc, String tenThuMuc)
        {
            if (maThuMuc != null)
            {
                ThuMucDTO thuMuc = _taiLieuReportService.GetThuMuc(maThuMuc).First();
                thuMuc.TenThuMuc = tenThuMuc;
                _taiLieuCommandService.SuaThuMuc(UserUtility.GetCurrentUser().MaNguoiDung,thuMuc);
                return Json(new { success = true });
            }
            return Json(new { success = false });
        }

        [HttpPost]
        public JsonResult XoaThuMuc(Guid? maThuMuc)
        {
            string message = string.Empty;
            try
            {
                if (maThuMuc != null)
                {
                    if (_taiLieuCommandService.XoaThuMuc(UserUtility.GetCurrentUser().MaNguoiDung, (Guid)maThuMuc))
                        return Json(new { success = true });
                    else
                        message = "Xóa thư mục không thành công.";
                }
                else
                    message = "";
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return Json(new { 
                success = false,
                message = message
            });
        }

        [HttpGet]
        public ActionResult GetCayThuMuc(Guid? maThuMucCha)
        {
            return PartialView("CayThuMuc",maThuMucCha);
        }

        [HttpGet]
        public ActionResult XemTaiLieu(Guid? maTaiLieu)
        {
            if (!maTaiLieu.HasValue)
                return HttpNotFound();
            else
            {
                CapNhatTaiLieuViewModel viewModel = new CapNhatTaiLieuViewModel();
                viewModel = CapNhatTaiLieuViewModel.FromTaiLieuDTO(_taiLieuReportService.GetTaiLieuById((Guid)maTaiLieu));
                return View(viewModel);
            }
        }

        [HttpGet]
        public ActionResult TaoTaiLieu(Guid? maTaiLieu, Guid? maThuMucCha)
        {
            CapNhatTaiLieuViewModel viewModel = new CapNhatTaiLieuViewModel();
            if (maTaiLieu != null)
            {
                viewModel = CapNhatTaiLieuViewModel.FromTaiLieuDTO(_taiLieuReportService.GetTaiLieuById((Guid)maTaiLieu));
                maThuMucCha = viewModel.MaThuMuc;
            }
            viewModel.DanhSachThuMuc = _taiLieuReportService.GetThuMuc(null);
            viewModel.DanhSachLoaiTaiLieu = _taiLieuReportService.GetLoaiTaiLieu(null);
            ViewData["maThuMucCha"] = maThuMucCha ?? Guid.Empty;
            ViewData["duongDanThuMuc"] = maThuMucCha != null ? _taiLieuReportService.GetDuongDanThuMuc((Guid)maThuMucCha) : String.Empty;
            return View(viewModel);
        }

        [HttpGet]
        public JsonResult GetDuongDanThuMuc(Guid maThuMuc)
        {
            string duongDan = _taiLieuReportService.GetDuongDanThuMuc(maThuMuc);
            return Json(new { duongDan = duongDan }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult TaoTaiLieu(CapNhatTaiLieuViewModel viewModel)
        {
             object jsonData;

             try
             {
                 if (ModelState.IsValid)
                 {
                     viewModel.PhanMoRong = Path.GetExtension(viewModel.TenTapTin);
                     viewModel.TenTapTin = Path.GetFileNameWithoutExtension(viewModel.TenTapTin);
                     if (viewModel.MaTaiLieu.Equals(Guid.Empty))
                     {
                         _taiLieuCommandService.InsertTaiLieu(UserUtility.GetCurrentUser().MaNguoiDung, viewModel.ToTaiLieuDTO());
                     }
                     else
                     {
                         _taiLieuCommandService.UpdateTaiLieu(UserUtility.GetCurrentUser().MaNguoiDung, viewModel.ToTaiLieuDTO());
                     }
                     jsonData = new
                     {
                         success = true,
                         message = "Tạo tài liệu thành công!"
                     };
                 }
                 else jsonData = new
                 {
                     success = false,
                     message = "Dữ liệu nhập vào không hợp lệ!"
                 };
             }
             catch (Exception exception)
             {
                 jsonData = new { 
                     success = false,
                     message = exception.Message
                 };
             }
            return Json(jsonData); 
        }

        [HttpPost]
        public JsonResult XoaTaiLieu(Guid? maTaiLieu)
        {
            object jsonResult;
            string message = string.Empty;
            try
            {
                if (maTaiLieu != null)
                {
                    var tailieu = _taiLieuReportService.GetTaiLieuById((Guid)maTaiLieu);
                    var maTapTin = tailieu.MaTapTin;
                    if (_taiLieuCommandService.DeleteTaiLieu(UserUtility.GetCurrentUser().MaNguoiDung, (Guid)maTaiLieu))
                    {
                        _fileService.DeleteFileById(maTapTin);
                        jsonResult = new
                        {
                            success = true
                        };
                    }
                    else
                    {
                        jsonResult = new
                        {
                            success = false,
                            message = "Không thể xóa tài liệu này."
                        };
                    }
                }
                else
                    jsonResult = new
                    {
                        success = false,
                        message = "Không thể xóa tài liệu này."
                    };
            }
            catch (Exception exception)
            {
                jsonResult = new
                {
                    success = false,
                    message = exception.Message
                };
            }
            return Json(jsonResult);
        }

        [HttpPost]
        public JsonResult UpLoadFile()
        {
            object jsonData;
            HttpPostedFileBase file = Request.Files[0];

            if (ModelState.IsValid && file != null)
            {
                Guid maTapTin = Guid.Empty;
                _fileService.SaveFileFromStream(null, file.InputStream, file.FileName, file.ContentType, out maTapTin);
                jsonData = new
                {
                    success = true,
                    fileName = file.FileName,
                    fileSize = file.ContentLength,
                    fileId = maTapTin
                };
            }
            else jsonData = new
            {
                success = false,
                message = "Tạo tài liệu không thành công!"
            };
            return Json(jsonData); 
        }

        [HttpGet]
        public PartialViewResult LayDanhSachTaiLieu(Guid? thuMucHienTai)
        {
            IEnumerable<DanhSachTaiLieuViewModel> danhSachTaiLieu = new List<DanhSachTaiLieuViewModel>();
            if (thuMucHienTai != null && !thuMucHienTai.Equals(Guid.Empty))
            {
                danhSachTaiLieu = DanhSachTaiLieuViewModel.FromTaiLieuDTOList(_taiLieuReportService.GetAllTaiLieu(thuMucHienTai, null, null, null, null));
            }
            return PartialView("DanhSachTaiLieuGrid",danhSachTaiLieu);
        }

        [HttpGet]
        public ActionResult TaiFile(Guid? fileId)
        {
            Stream fileStream;
            String fileName;
            String contentType;
            if (fileId == null || !_fileService.GetFileStreamById((Guid)fileId, out fileStream, out fileName, out contentType))
                return new HttpNotFoundResult("File not found");
            Response.BufferOutput = false;
            FileStreamResult fileStreamResult = new FileStreamResult(fileStream, contentType)
            {
                FileDownloadName = fileName
            };
            return fileStreamResult;
        }

        [HttpGet]
        [GiangVienAuthorize(AllowAnonymous=true)]
        public ActionResult TaiFileTaiLieu(Guid? taiLieuId)
        {
            if (taiLieuId.HasValue)
            {
                Stream fileStream;
                String fileName;
                String contentType;
                Response.BufferOutput = false;
                var taiLieu = _taiLieuReportService.GetTaiLieuById(taiLieuId.Value);
                if (taiLieu != null)
                {
                    if (_fileService.GetFileStreamById(taiLieu.MaTapTin, out fileStream, out fileName, out contentType))
                    {
                        FileStreamResult fileStreamResult = new FileStreamResult(fileStream, contentType)
                        {
                            FileDownloadName = fileName
                        };
                        return fileStreamResult;
                    }
                    else
                        return new HttpNotFoundResult("File not found.");
                }
                else
                    return new HttpNotFoundResult("File not found."); 
            }
            else
            {
                return new HttpNotFoundResult("File not found.");
            }

        }

        [HttpGet]
        public ActionResult ChonTaiLieuDialog(Guid? maNguoiDung)
        {
            ChonTaiLieuViewModel viewModel = new ChonTaiLieuViewModel();
            viewModel.maNguoiDung = Guid.Empty;
            return View(viewModel);
        }

        [HttpGet]
        public ActionResult ChonTaiLieuGrid(Guid? thuMucHienTai)
        {
            IEnumerable<DanhSachTaiLieuViewModel> danhSachTaiLieu = new List<DanhSachTaiLieuViewModel>();
            if (thuMucHienTai != null && !thuMucHienTai.Equals(Guid.Empty))
            {
                danhSachTaiLieu = DanhSachTaiLieuViewModel.FromTaiLieuDTOList(_taiLieuReportService.GetAllTaiLieu(thuMucHienTai, null, null, null, null));
            }
            return PartialView("ChonTaiLieuGrid", danhSachTaiLieu);
        }

        //Guid AdminId {
        //    get { 
        //        Guid adminId;
        //        if (Guid.TryParse(_thamSoService.GetThamSo("MaAdmin"), out adminId))
        //            return adminId;
        //        else
        //            return Guid.Empty;
        //    }
        //}
    }
}
